<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
// use App\Models\Certificate;
// use App\Models\Member;
use Illuminate\Support\Facades\Http;
use Auth;
use LaravelJsTan\Facades\JsTan;
use JsTan\Client;
use JsTan\Route;
use Log;
use App\Services\JsTan\Ecshop;

class KuajingyunController extends Controller
{

    /**
     * @api {post} /kuajingyun/test
     * 跨境云测试
     */
    public function test(Request $request)
    {
        $goodsList = [
            [
                'goodsIndex' => 1,
                'platformProCode' => '872319437021',
                'platformProName' => '麦片早餐减重低脂全麦桂格即食燕麦片',
                'price' => 200.3,
                'num' => 1,
                'goodsTotalTax' => 10.8
            ]
        ];

        $params = [
            'platformOrderNo' => '202209019992',
            'declareNo' => 'PAY202209019992',
            'orderTime' => date('Y-m-d H:i:s'),
            'payTime' => date('Y-m-d H:i:s'),
            'payNo' => '420024548784561548723',
            'payType' => '4403169D3W',
            'buyerId' => '1365845871',
            'buyerIdno' => '511081198201270628',
            'buyerIdnoFront' => 'http://image.ccs.ustarvs.com/storage/app/public/uploads/certificate/20250227/511081198201270628-reverse.jpeg',
            'buyerIdnoBack' => 'http://image.ccs.ustarvs.com/storage/app/public/uploads/certificate/20250227/511081198201270628-front.jpeg',
            'buyerName' => '李英',
            'buyerPhone' => '13521254125',
            'consigneeProvince' => '广东省',
            'consigneeCity' => '广州市',
            'consigneeArea' => '越秀区',
            'consigneeAddress' => '海珠街道阳光小区3栋200',
            'consigneeFullAddress' => '广东省广州市越秀区海珠街道阳光小区3栋2001',
            'consignee' => '林先生',
            'consigneePhone' => '13521254125',
            'logisFee' => 1.4,
            'disFee' => 10.0,
            'taxFee' => 10.8,
            'goodsFee' => 400.6,
            'payFee' => 402.8,
            'platformCode' => 'JX001',
            'shopCode' => 'DP001',
            // 'customsMode' => 2,
            'ebpCode' => '322321122X',
            'ebpName' => '直邮商城',
            'goodsList' => json_encode($goodsList),

        ];

        $url = 'http://oms.cbcscm.com:28888/api/oms';
        $params_['method'] = 'oms.orderPush';
        $params_['appkey'] = '1661196333749116930';
        $params_['bizcontent'] = json_encode($params);
        $params_['timestamp'] = time();
        // $params_['sign'] = ;

        $privateKey = '6b868615b118447783135f4bf8e9c5bd';
        $sign = self::generateSignature($params, $privateKey);
        dd($sign);
        $result = self::sendPost($url, $params);
        dd($url, $params, $result);

    }

    public static function sendPost($url, $data)
    {
        // dd($url, $data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($res, 1);
        return $res;
    }

    /**
     * 生成RSA签名
     *
     * @param array $params 需要签名的参数数组（必须包含处理后的bizcontent）
     * @param string $privateKey 商户私钥（PEM格式）
     *
     * @return string Base64编码的签名结果
     * @throws Exception 签名失败时抛出异常
     */
    public static function generateSignature($params, $privateKey)
    {
        // 1. 过滤空值参数
        $filteredParams = array_filter($params, function($value) {
            return $value !== null && $value !== '';
        });
// dd($filteredParams);
        // 2. 按参数名ASCII字典序排序
        ksort($filteredParams);

        // 3. 拼接键值对字符串
        $signString = '';
        foreach ($filteredParams as $key => $value) {
            $signString .= $key . '=' . $value . '&';
        }
        $signString = rtrim($signString, '&');

        // 4. 加载私钥
        $privateKeyResource = openssl_pkey_get_private($privateKey);
        // dd($privateKeyResource);
        if ($privateKeyResource === false)
        {
            // throw new Exception('无法加载私钥，请检查私钥格式是否正确');
            return false;
        }

        // 5. 使用SHA256WithRSA算法签名
        $signature = '';
        if (!openssl_sign($signString, $signature, $privateKeyResource, OPENSSL_ALGO_SHA256)) {
            // throw new Exception('签名生成失败：' . openssl_error_string());
            return false;
        }

        // 6. 释放密钥资源
        openssl_free_key($privateKeyResource);

        // 7. 返回Base64编码结果
        return base64_encode($signature);
    }

    /**
     * 解密业务数据
     *
     * @param string $encryptedData URL编码后的加密字符串
     * @param string $privateKey    商户私钥(PEM格式)
     *
     * @return string 解密后的原始JSON数据
     * @throws Exception 解密失败时抛出异常
     */
    // function decryptBizContent(string $encryptedData, string $privateKey): string {
    //     // 1. URL解码
    //     $urlDecoded = urldecode($encryptedData);

    //     // 2. Base64解码
    //     $base64Decoded = base64_decode($urlDecoded);
    //     if ($base64Decoded === false) {
    //         throw new Exception("Base64解码失败");
    //     }

    //     // 3. 加载私钥
    //     $privateKeyResource = openssl_pkey_get_private($privateKey);
    //     if ($privateKeyResource === false) {
    //         throw new Exception("私钥格式错误，请检查PEM格式");
    //     }

    //     // 4. 分段解密（处理长文本）
    //     $chunkSize = 256; // RSA2048的块大小
    //     $output = '';
    //     $offset = 0;

    //     while ($offset < strlen($base64Decoded)) {
    //         $chunk = substr($base64Decoded, $offset, $chunkSize);
    //         $decryptedChunk = '';

    //         if (!openssl_private_decrypt(
    //             $chunk,
    //             $decryptedChunk,
    //             $privateKeyResource,
    //             OPENSSL_PKCS1_PADDING
    //         )) {
    //             openssl_free_key($privateKeyResource);
    //             throw new Exception("解密失败：".openssl_error_string());
    //         }

    //         $output .= $decryptedChunk;
    //         $offset += $chunkSize;
    //     }

    //     // 5. 释放资源
    //     openssl_free_key($privateKeyResource);

    //     return $output;
    // }



    /**
     * @api {post} /jstan/upload_skumap
     * 店铺商品资料上传
     */
    public function upload_skumap(Request $request)
    {
        $request = $request->all();

        $shop_items = json_decode($request['shop_items'], 1);

        $response = JsTan::Client()->request(
            Route::UPLOAD_SKUMAP, $shop_items
        );
        $response = json_decode($response, 1);
        // dd(config('jsTan'),$response);

        return $response;
    }

    /**
     * @api {post} /jstan/upload_itemsku
     * 普通商品资料上传
     */
    public function upload_itemsku(Request $request)
    {
        $request = $request->all();

        $goods_items = json_decode($request['goods_items'], 1);

        $response = JsTan::Client()->request(
            Route::UPLOAD_ITEMSKU, $goods_items
        );
        $response = json_decode($response, 1);
        // dd(config('jsTan'),$response);

        return $response;
    }

    /**
     * @api {post} /jstan/upload_orders
     * 订单上传
     */
    public function upload_orders(Request $request)
    {
        $request = $request->all();

        $order_params = json_decode($request['order_params'], 1);

        $response = JsTan::Client()->request(
            Route::UPLOAD_ORDERS, $order_params
        );
        $response = json_decode($response, 1);
        // dd(config('jsTan'),$response);

        return $response;
    }


    /**
     * @api {post} /shop/order_delivery
     * 接收:订单发货
     */
    public function order_delivery(Request $request)
    {
        $request = $request->all();

        //{"o_id":1,"l_id":"test","so_id":"test","lc_id":"test","order_from":"test","wms_co_id":0,"logistics_company":"test","send_date":"2024-12-08 23:46:01.687","items":[{"oi_id":1,"sku_id":"test","qty":1,"name":"test","outer_oi_id":"test","so_id":"test"}],"ts":"1733672761","partnerid":"erp","method":"logistics.upload","sign":"4df98d6c1534e6d2b644cfb0478e6b89"}

        // {"o_id":167859,"l_id":"DEUHYD400066038247EU","so_id":"2023022852799","lc_id":"\u8d27\u6613\u8fbe__12","order_from":"open","wms_co_id":13659696,"logistics_company":"\u4e5d\u8058","send_date":"2024-12-08 23:52:37.019",items":[],"ts":"1733673157","partnerid":"erp","method":"logistics.upload","sign":"ab007bad85ab2107cb5f1ec83d2cf9e9"}

        Log::info('order_delivery_request:'. json_encode($request));

        $msg = '';
        $res = Ecshop::orderDelivery($request, $msg);
        // dd('sss',$res, $msg);
        if (!$res)
        {
            $result = ['code' => 500, 'msg' => $msg];
        }
        else
        {
            $result = ['code' => 0, 'msg' => '执行成功'];
        }

        return json_encode($result);
    }

    /**
     * @api {get} /jstan/order_cancel
     * 接收：订单取消
     */
    public function order_cancel(Request $request)
    {
        $request = $request->all();

        Log::info('order_cancel_request:'. json_encode($request));

        // $request = '{"so_id":"2024120866708","remark":"test","ts":"1733672762","partnerid":"erp","method":"cancel.order","sign":"aaad138d970f219d76bfdba9f1608dc0"}';

        // $request = json_decode($request, 1);

        $msg = '';
        $res = Ecshop::orderCancel($request, $msg);
        // dd('sss',$res, $msg);
        if (!$res)
        {
            $result = ['code' => 500, 'msg' => $msg];
        }
        else
        {
            $result = ['code' => 0, 'msg' => '执行成功'];
        }

        return json_encode($result);
    }

    /**
     * @api {get} /shop/update_inventory
     * 接收：更新库存
     */
    public function update_inventory(Request $request)
    {
        $request = $request->all();

        Log::info('update_inventory_request:'. json_encode($request));

        // $request = '{"datas":[{"i_id":null,"id":0,"qty":100,"shop_i_id":"test","shop_id":0,"shop_sku_id":"test","sku_id":"sandancesensitiv2","sku_source":null,"modified":"2024-12-09 20:20:20"}],"ts":"1733672762","partnerid":"erp","method":"inventory.upload","sign":"352ba02ba39c1a5c387a0a7d45cdc81b"}';

        // $request = json_decode($request, 1);

        $msg = '';
        $res = Ecshop::updateInventory($request, $msg);
        // dd('sss',$res, $msg);
        if (!$res)
        {
            $result = ['code' => 500, 'msg' => $msg];
        }
        else
        {
            $result = ['code' => 0, 'msg' => '执行成功'];
        }

        return json_encode($result);
    }

    /**
     * @api {get} /shop/confirm_delivery
     * 接收：确认收货
     */
    public function confirm_delivery(Request $request)
    {
        $request = $request->all();

        // confirm_delivery_request:{"action_name":"\u786e\u8ba4\u6536\u8d27","as_id":1,"o_id":"test","outer_as_id":"test","remark":"test","shop_id":17292311,"so_id":"test","unique_id":"a500be35-c9c8-4703-a5bb-40aac288c6ff","items":[{"qty":1,"sku_id":"test"}],"ts":"1733672762","partnerid":"erp","method":"refund.goods","sign":"2bc2b67934513a24eef4ca8d7eb50726"}
        Log::info('confirm_delivery_request:'. json_encode($request));

        $msg = '';
        $res = Ecshop::confirmDelivery($request, $msg);
        // dd('sss',$res, $msg);
        if (!$res)
        {
            $result = ['code' => 500, 'msg' => $msg];
        }
        else
        {
            $result = ['code' => 0, 'msg' => '执行成功'];
        }

        return json_encode($result);
    }

}
